﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Alogient.Cameleon.Sdk.UI.WebControls
{
    public class CustomAdminMasterPage : System.Web.UI.MasterPage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            string sessionID = Request["SessionID"];
            string path = string.Format("{0}/CustomAdminWebService.asmx/ValidAccess?SessionID={1}", CMSettings.AdminUrl, sessionID);
            string response = HttpGET(path);

            //bool validAccess = response.ToLower().IndexOf("true") > 0;

            //if (!validAccess)
            //{
            //    Response.Redirect(CMSettings.AdminUrl);
            //}
        }

        public static string HttpGET(string uri)
        {
            // parameters: name1=value1&name2=value2	
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(uri);

            if (webRequest == null)
                throw new WebException(string.Format("HttpWebRequest webRequest Occured: URI: {0} || AdminUrl: {1}", uri, CMSettings.AdminUrl));

            webRequest.Method = "GET";

            System.Net.ServicePointManager.Expect100Continue = false;

            // get the response
            webRequest.Expect = "text/richtext";// "text/xml";

            HttpWebResponse webResponse;
            try
            {
                webResponse = (HttpWebResponse)webRequest.GetResponse();
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("webRequest.GetResponse() Occured: URI: {0} || AdminUrl: {1} || Exception: {2}", uri, CMSettings.AdminUrl, ex.Message));
            }

            if (webResponse == null)
            {
                throw new WebException(string.Format("HttpWebResponse webResponse Occured: URI: {0} || AdminUrl: {1}", uri, CMSettings.AdminUrl));
            }

            var sr = new StreamReader(webResponse.GetResponseStream());

            return sr.ReadToEnd().Trim();
        } // end HttpGET
    }
}
